/*******************************************************************

    Author: Xiao
    Date: 2022/3/28 17:18

*******************************************************************/

package controller

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"mcr/pkg/config"
	"mcr/pkg/logs"
	"mcr/pkg/middleware"
	"net/http"
	"strings"
	"time"
)

func InitHTTPRegister(app *gin.Engine) {
	app.Use(Cors())
	app.LoadHTMLFiles("static/index.html")
	app.GET("/", func(ctx *gin.Context) {
		ctx.HTML(http.StatusOK, "index.html", nil)
	})
	app.Static("/uploads", "./uploads")
	app.Static("/static", "./static")
	app.Static("/new", "./new")
	app.Static("/api/song/uploads", "./uploads")
	// 注册websocket
	app.GET("/socket", ConnWebsocket)
	router := app.Group("/api")
	smsGroup := router.Group("/sms")
	{
		smsGroup.POST("/email", SendEmailVerify)
	}
	userGroup := router.Group("/user")
	{
		userGroup.POST("/login", LoginUser)
		userGroup.POST("/online", GetOnlines)
		userGroup.POST("/getuserinfo", BeforeJwtCheck, GetUserInfo)
		userGroup.POST("/getmyinfo", BeforeJwtCheck, GetMyInfo)
		userGroup.POST("/updateMyInfo", BeforeJwtCheck, UpdateUserInfo)
		userGroup.POST("/guestctrl", BeforeJwtCheck, PostGuestctrl)
		userGroup.POST("/shutdown", BeforeJwtCheck, PostShutdown)
		userGroup.POST("/songdown", BeforeJwtCheck, PostSongDown)
		userGroup.POST("/removeban", BeforeJwtCheck, PostRemoveBan)
	}
	attachGroup := router.Group("/attach")
	{
		attachGroup.POST("/uploadimage", BeforeJwtCheck, UploadImage)
		attachGroup.POST("/uploadImage", BeforeJwtCheck, UploadImage)
		attachGroup.POST("/uploadHead", BeforeJwtCheck, UploadHead)
		attachGroup.POST("/uploadMusic", BeforeJwtCheck, UploadMusic)
	}
	roomGroup := router.Group("/room")
	{
		roomGroup.POST("/getRoomInfo", BeforeJwtCheck, GetRoomInfo)
		roomGroup.POST("/getWebsocketUrl", BeforeJwtCheck, GetWebsocketUrl)
		roomGroup.POST("/myRoom", BeforeJwtCheck, GetMyRoom)
		roomGroup.POST("/create", BeforeJwtCheck, CreateRoom)
		roomGroup.POST("/hotRooms", BeforeJwtCheck, GetHotRooms)
		roomGroup.POST("/saveMyRoom", BeforeJwtCheck, UpdateRoomSetting)
	}
	songGroup := router.Group("/song")
	{
		songGroup.POST("/search", BeforeJwtCheck, SearchSong)
		songGroup.POST("/getLrc", BeforeJwtCheck, GetLrc)
		songGroup.POST("/playurl", BeforeJwtCheck, PlayUrl)
		songGroup.GET("/playurl", PlayUrlGet)
		songGroup.POST("/pass", BeforeJwtCheck, PassSong)
		songGroup.POST("/addSong", BeforeJwtCheck, AddSong)
		songGroup.POST("/playSong", BeforeJwtCheck, PlaySong)
		songGroup.POST("/songList", BeforeJwtCheck, SongList)
		songGroup.POST("/push", BeforeJwtCheck, PushSong)
		songGroup.POST("/remove", BeforeJwtCheck, RemoveSong)
		songGroup.POST("/mySongList", BeforeJwtCheck, GetMySongList)
		songGroup.POST("/getusersongs", BeforeJwtCheck, GetUserSongs)
		songGroup.POST("/addMySong", BeforeJwtCheck, AddMySong)
		songGroup.POST("/addNewSong", BeforeJwtCheck, AddNewSong)
		songGroup.POST("/deleteMySong", BeforeJwtCheck, DeleteMySong)
		songGroup.POST("/now", BeforeJwtCheck, NowTimeSong)
	}
	messageGroup := router.Group("/message")
	{
		messageGroup.POST("/send", BeforeJwtCheck, Send)
		messageGroup.POST("/touch", BeforeJwtCheck, Touch)
		messageGroup.POST("/back", BeforeJwtCheck, BackMessage)
		messageGroup.POST("/clear", BeforeJwtCheck, ClearMessage)
		messageGroup.POST("/getMessageList", BeforeJwtCheck, GetMessageList)
	}
	sysGroup := router.Group("/system")
	{
		sysGroup.POST("time", func(ctx *gin.Context) {
			data := make(map[string]interface{})
			data["time"] = time.Now().UnixNano() / 1e6
			ctx.JSON(200, gin.H{
				"code": 200,
				"msg":  "获取服务时间",
				"data": data,
			})
			return
		})
	}
}

// 请求的基础参数
type BasicReq struct {
	Plat        string `json:"plat" binding:"required"`
	Version     int    `json:"version" binding:"required"`
	AccessToken string `json:"access_token" binding:"required"`
}

// 鉴权中间件
func BeforeJwtCheck(ctx *gin.Context) {
	if config.ConfigValue.Debug == true {
		ctx.Next()
	} else {
		token := ctx.PostForm("access_token")
		if token == "" {
			data, err := ctx.GetRawData()
			if err != nil {
				logs.Log.Errorf("参数获取失败:%s", err)
				ctx.JSON(200, gin.H{
					"code": 400,
					"msg":  "参数获取失败!",
				})
				ctx.Abort()
				return
			}
			var br BasicReq
			err = json.Unmarshal(data, &br)
			if err != nil {
				ctx.JSON(200, gin.H{
					"code": 401,
					"msg":  "参数不合法!",
				})
				ctx.Abort()
				return
			}
			// 重新写入body
			ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(data))
			token = br.AccessToken
		}
		if token == "" {
			ctx.JSON(200, gin.H{
				"code": 400,
				"msg":  "AccessToken为必要参数!",
			})
			ctx.Abort()
			return
		}
		if token == config.ConfigValue.GuestToken {
			ctx.Next()
			return
			//ctx.JSON(401,gin.H{
			//	"msg":"请登录后体验完整功能!",
			//})
		}
		if ok, errMsg := middleware.CheckJwtAuth(token); ok {
			ctx.Next()
		} else {
			ctx.JSON(200, gin.H{
				"code": 401,
				"msg":  errMsg,
			})
			ctx.Abort()
			return
		}
	}
}

// Cors 开放所有接口的OPTIONS方法
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method               //请求方法
		origin := c.Request.Header.Get("Origin") //请求头部
		var headerKeys []string                  // 声明请求头keys
		for k, _ := range c.Request.Header {
			headerKeys = append(headerKeys, k)
		}
		headerStr := strings.Join(headerKeys, ", ")
		if headerStr != "" {
			headerStr = fmt.Sprintf("access-control-allow-origin, access-control-allow-headers, %s", headerStr)
		} else {
			headerStr = "access-control-allow-origin, access-control-allow-headers"
		}
		if origin != "" {
			origin := c.Request.Header.Get("Origin")
			c.Header("Access-Control-Allow-Origin", origin)                                    // 这是允许访问所有域
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE") //服务器支持的所有跨域请求的方法,为了避免浏览次请求的多次'预检'请求
			//  header的类型
			c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
			//              允许跨域设置                                                                                                      可以返回其他子段
			c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar") // 跨域关键设置 让浏览器可以解析
			c.Header("Access-Control-Max-Age", "172800")                                                                                                                                                           // 缓存请求信息 单位为秒
			c.Header("Access-Control-Allow-Credentials", "false")                                                                                                                                                  //  跨域请求是否需要带cookie信息 默认设置为true
			c.Set("content-type", "application/json")                                                                                                                                                              // 设置返回格式是json
		}

		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.JSON(http.StatusOK, "Options Request!")
		}
		// 处理请求
		c.Next() //  处理请求
	}
}
